const AlipaySdk = require("alipay-sdk").default;
require('dotenv').config(); // 加载 .env 文件到 process.env

const {ZFB_APPID, ZFB_PUBLIC_KEY, ZFB_PRIVATE_KEY} = process.env

const appId = ZFB_APPID

const alipaySdk = new AlipaySdk({
    appId,
    privateKey: ZFB_PRIVATE_KEY,
    alipayPublicKey: ZFB_PUBLIC_KEY,
    gateway: "https://openapi.alipay.com/gateway.do",
});

class Alipay {

    async getOauthToken(authCode, isRefreshToken = false) {
        try {
            const res = await alipaySdk.exec("alipay.system.oauth.token", {
                code: authCode,
                grant_type: !isRefreshToken ? "authorization_code" : "refresh_token",
                // refresh_token: "201208134b203fe6c11548bcabd8da5bb087a83b",
            });
            return res;
        } catch (e) {
            console.log(e);
            throw ({msg: e})
        }
    }

    async getAliPayUserInfo(auth_token) {
        try {
            let res = await alipaySdk.exec("alipay.user.info.share", {
                auth_token
            });
            return res
        } catch (e) {
            console.log(e, '错误信息');
            throw ({msg: e.message})
        }
    }

    async createAlipayTrade(ctx, user_id, openId) {
        // const {authCode} = ctx.request.query;
        try {
            let res = await alipaySdk.exec("alipay.trade.create", {
                bizContent: {
                    out_trade_no: Number(Math.random().toString().substr(3, 0) + '' +
                        Date.now()).toString(36),
                    total_amount: 1.00,
                    subject: '测试',
                    op_app_id: appId,
                    // product_code: 2088741436668559,
                    product_code: 'JSAPI_PAY', //小程序写死JSAPI_PAY
                    buyer_open_id: '023iS3anXAf6ou3gMj7R9SAfNbkN9vH8GDsesnegTE2bjA9',
                    // buyer_id: openId,
                    op_buyer_open_id: openId
                }
            });
            return res
        } catch (e) {
            console.log(e, '错误信息');
            throw ({msg: e.message})
        }
    }
}

module.exports = new Alipay()
